package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @description
 * @author: ZXX-挚爱
 * @time: 2023/7/20 1:11
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class LessonChangeListener {

    private final ILearningLessonService lessonService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),
                    exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
                    key =MqConstants.Key.ORDER_PAY_KEY
            )
    )
    public void listenerLessonPay(OrderBasicDTO order){

        //健壮性判断
        if(order==null || order.getUserId()==null || CollUtils.isEmpty(order.getCourseIds())){
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        log.info("监听到用户{}的订单{}，需要添加课程{}到课表中",order.getUserId(),order.getOrderId(),order.getCourseIds());
        //添加课程信息
        lessonService.addUserLessons(order.getUserId(),order.getCourseIds());
    }

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "learning.lesson.refund.queue",durable = "true"),
                    exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE,type = ExchangeTypes.TOPIC),
                    key = MqConstants.Key.ORDER_REFUND_KEY
            )
    )
    public void listenerLessonRefund(OrderBasicDTO order){
        if (order==null || order.getUserId()==null || CollUtils.isEmpty(order.getCourseIds())){
            log.error("接收到MQ消息有误，订单数据为空");
        }

        log.debug("监听到用户{}的订单{}，需要删除课程{}",order.getUserId(),order.getOrderId(),order.getCourseIds());
        lessonService.deleteMyLessonByCourseId(order.getUserId(),order.getCourseIds().get(0));
    }


}
